package com.angel.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

/*异步加载图片类*/
public class AsyncDownload {
		private static AsyncDownload asyncDownload;
		private HashMap<String,SoftReference<Drawable>> map=new HashMap<String,SoftReference<Drawable>>();
		SoftReference<Drawable> softReference;
		private Drawable drawable;
		private AsyncDownload(){
//			map=new HashMap<String,SoftReference<Drawable>>();
		}
		/*创建单例*/
		public static AsyncDownload getInstance(){
			if(asyncDownload==null){
				asyncDownload=new AsyncDownload();
			}
				return asyncDownload;
		}
		/*回调函数，根据软引用中对象是否存在，从而决定是否下载*/
		public  Drawable imageDown(final ImageView img,final String url,final CallBack callBack){
			if(map.containsKey(url)){//判断是否存在地址
				softReference=map.get(url);
				drawable=softReference.get();
				if(drawable!=null){
					return drawable;
				}else{
				//	map.remove(url);
				}
			}
			/*将结果回调设置*/
			final Handler handler=new Handler(){
			   public void handleMessage(Message msg){
				   Log.i("asyncDownLoad","handler drawable:"+msg.obj);
				   callBack.imgDown(img,(Drawable)msg.obj);
			   }
			};
			class MyThread extends Thread{
				public void run(){
					drawable=downloadImg(url);
					Message msg=handler.obtainMessage();
					SoftReference<Drawable> soft=new SoftReference<Drawable>(drawable);
					map.put(url, soft);
				    
					Log.i("asyncDownLoad","softget:"+soft.get());
  					msg.obj=soft.get();

  					handler.sendMessage(msg);
				}
			}
			new MyThread().start();
			return null;
		}
		/*根据地址下载，获取Drawable对象*/
		public Drawable downloadImg(String address){
			URL url;
			InputStream inStream;
			Drawable drawable=null;
			try {
				url=new URL(address);
				inStream=(InputStream)url.getContent();
				drawable=Drawable.createFromStream(inStream,"src");
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return drawable;
		}
		public interface CallBack{
			public void imgDown(ImageView img,Drawable drawable);
		}
}
